const { Warning, User } = require('../models');
const weatherApi = require('../utils/weatherApi');
const taskScheduler = require('../utils/taskScheduler');
const emailService = require('../utils/emailService');

// 获取用户的所有预警设置
exports.getUserWarnings = async (req, res) => {
  try {
    const userId = req.user.id;
    
    const warnings = await Warning.findAll({
      where: { userId },
      order: [['createdAt', 'DESC']]
    });
    
    res.status(200).json({
      status: 'success',
      results: warnings.length,
      data: {
        warnings
      }
    });
  } catch (error) {
    console.error('获取用户预警设置失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

// 创建新的预警设置
exports.createWarning = async (req, res) => {
  try {
    const userId = req.user.id;
    const {
      location,
      locationName,
      triggerTime,
      isCountdown,
      countdownMinutes
    } = req.body;
    
    // 参数校验
    if (!location || !locationName) {
      return res.status(400).json({
        status: 'fail',
        message: '请提供地点ID和地点名称'
      });
    }
    
    if (!isCountdown && !triggerTime) {
      return res.status(400).json({
        status: 'fail',
        message: '请提供触发时间或设置为倒计时模式'
      });
    }
    
    if (isCountdown && (!countdownMinutes || countdownMinutes <= 0)) {
      return res.status(400).json({
        status: 'fail',
        message: '请提供有效的倒计时分钟数'
      });
    }
    
    // 创建预警设置
    let warningData = {
      userId,
      location,
      locationName,
      isCountdown: !!isCountdown,
      isActive: true
    };
    
    if (isCountdown) {
      warningData.countdownMinutes = countdownMinutes;
      // 计算触发时间
      const triggerDate = new Date();
      triggerDate.setMinutes(triggerDate.getMinutes() + countdownMinutes);
      warningData.triggerTime = triggerDate;
    } else {
      warningData.triggerTime = new Date(triggerTime);
    }
    
    // 保存到数据库
    const warning = await Warning.create(warningData);
    
    // 创建定时任务
    taskScheduler.scheduleWarningTask(warning);
    
    res.status(201).json({
      status: 'success',
      data: {
        warning
      }
    });
  } catch (error) {
    console.error('创建预警设置失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

// 获取单个预警设置详情
exports.getWarning = async (req, res) => {
  try {
    const userId = req.user.id;
    const { id } = req.params;
    
    const warning = await Warning.findOne({
      where: { id, userId }
    });
    
    if (!warning) {
      return res.status(404).json({
        status: 'fail',
        message: '找不到该预警设置'
      });
    }
    
    res.status(200).json({
      status: 'success',
      data: {
        warning
      }
    });
  } catch (error) {
    console.error('获取预警设置详情失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

// 更新预警设置
exports.updateWarning = async (req, res) => {
  try {
    const userId = req.user.id;
    const { id } = req.params;
    const {
      location,
      locationName,
      triggerTime,
      isCountdown,
      countdownMinutes,
      isActive
    } = req.body;
    
    // 查找预警设置
    const warning = await Warning.findOne({
      where: { id, userId }
    });
    
    if (!warning) {
      return res.status(404).json({
        status: 'fail',
        message: '找不到该预警设置'
      });
    }
    
    // 更新字段
    if (location !== undefined) warning.location = location;
    if (locationName !== undefined) warning.locationName = locationName;
    if (isActive !== undefined) warning.isActive = isActive;
    
    // 处理触发时间和倒计时
    if (isCountdown !== undefined) warning.isCountdown = isCountdown;
    
    if (warning.isCountdown) {
      if (countdownMinutes !== undefined && countdownMinutes > 0) {
        warning.countdownMinutes = countdownMinutes;
        // 重新计算触发时间
        const triggerDate = new Date();
        triggerDate.setMinutes(triggerDate.getMinutes() + countdownMinutes);
        warning.triggerTime = triggerDate;
      }
    } else if (triggerTime !== undefined) {
      warning.triggerTime = new Date(triggerTime);
    }
    
    // 保存更新
    await warning.save();
    
    // 更新定时任务
    if (warning.isActive) {
      taskScheduler.scheduleWarningTask(warning);
    } else {
      taskScheduler.cancelWarningTask(warning.id);
    }
    
    res.status(200).json({
      status: 'success',
      data: {
        warning
      }
    });
  } catch (error) {
    console.error('更新预警设置失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

// 删除预警设置
exports.deleteWarning = async (req, res) => {
  try {
    const userId = req.user.id;
    const { id } = req.params;
    
    // 查找预警设置
    const warning = await Warning.findOne({
      where: { id, userId }
    });
    
    if (!warning) {
      return res.status(404).json({
        status: 'fail',
        message: '找不到该预警设置'
      });
    }
    
    // 取消定时任务
    taskScheduler.cancelWarningTask(warning.id);
    
    // 删除记录
    await warning.destroy();
    
    res.status(200).json({
      status: 'success',
      message: '预警设置已删除'
    });
  } catch (error) {
    console.error('删除预警设置失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

// 手动获取当前预警信息
exports.getCurrentWarnings = async (req, res) => {
  try {
    const { location } = req.query;
    
    if (!location) {
      return res.status(400).json({
        status: 'fail',
        message: '请提供地点ID或经纬度'
      });
    }
    
    // 调用和风天气API获取预警信息
    const warningData = await weatherApi.getWeatherWarnings(location);
    
    res.status(200).json({
      status: 'success',
      data: warningData
    });
  } catch (error) {
    console.error('获取当前预警信息失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

// 发送测试邮件
exports.sendTestEmail = async (req, res) => {
  try {
    const user = req.user;
    const result = await emailService.sendTestEmail(user.email);
    
    if (result.success) {
      res.status(200).json({
        status: 'success',
        message: '测试邮件已发送',
        data: result
      });
    } else {
      res.status(500).json({
        status: 'fail',
        message: '发送测试邮件失败',
        error: result.error
      });
    }
  } catch (error) {
    console.error('发送测试邮件失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
}; 